<template>
	<div>
		<el-row>
			<el-col :span="5">
				<el-input placeholder="请输入用户名称" v-model="p_user_name">
					<template slot="prepend">用户名称:</template>
				</el-input>
			</el-col>
			<el-col :span="19">
				<el-button type="primary" @click="showdata">查询</el-button>
				<el-button type="primary" @click="showAdd">增加</el-button>
				<el-button type="primary" @click="showDel" >删除</el-button>
				<el-button type="primary" @click="showExport" >导出</el-button>
				<el-button type="primary" @click="showDistribution" >分配</el-button>
				<el-button type="primary" @click="showCopybution(0)" >覆盖权限</el-button>
				<el-button type="primary" @click="showCopybution(1)" >追加权限</el-button>
				<!-- <el-button type="primary" @click="showShopDialog">追加店铺权限</el-button> -->
			</el-col>
		</el-row>
			
		<v-table :chart-data=userDate :items-data=itemsDate v-on:onEdit="showEdit" v-on:selectionChange="handleSelectionChange"></v-table>

		<!--新增界面-->
		<el-dialog :title="text" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')" style="padding-bottom:0;">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm"
			style="height:380px;">
				<el-form-item label="用户ID" prop="user_id">
					<el-input v-model="addForm.user_id" auto-complete="off" placeholder="请输入用户ID"></el-input>
				</el-form-item>
				<el-form-item label="用户姓名" prop="user_name">
					<el-input v-model="addForm.user_name" auto-complete="off" placeholder="请输入用户姓名"></el-input>
				</el-form-item>
				<el-form-item label="性别" prop="sex">
					<el-radio v-model="addForm.sex" label="男">男</el-radio>
  					<el-radio v-model="addForm.sex" label="女">女</el-radio>
				</el-form-item>
				<el-form-item label="联系电话" prop="telphone">
					<el-input v-model="addForm.telphone" auto-complete="off" placeholder="请输入联系电话"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobilephone">
					<el-input v-model="addForm.mobilephone" auto-complete="off" placeholder="请输入手机"></el-input>
				</el-form-item>
				<el-form-item label="联系地址" prop="address">
					<el-input v-model="addForm.address" auto-complete="off" placeholder="请输入联系地址"></el-input>
				</el-form-item>
				<!--<el-form-item label="部门归属" prop="address">
					<el-input v-model="addForm.address" auto-complete="off" placeholder="请输入联系地址"></el-input>
				</el-form-item>-->
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: left; margin-left:30px;margin-left:80px;">
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
				<el-button @click="reset()">重置</el-button>
			</div>
		</el-dialog>
		
		<el-dialog title="分配角色" :visible.sync="addRoleVisible" width="30%" @close="handleClose">
			<span>选择角色</span>
			<el-select v-model="checkedRole" filterable multiple placeholder="请选择">
				<el-option v-for="item in noRoleUserData" :key="item.role_key" :label="item.role_name" :value="item.role_key">
				</el-option>
			</el-select>
			<span slot="footer" class="dialog-footer">
			    <el-button @click="addRoleVisible = false;">取 消</el-button>
			    <el-button type="primary" @click="addRole">确 定</el-button>
			  </span>
		</el-dialog>
		
		<el-dialog title="复制权限" :visible.sync="addCopyRole" width="30%" @close="handleClose">
			<span>选择用户</span>
			<el-select v-model="checkedRoleUser" filterable multiple placeholder="请选择">
				<el-option v-for="item in RoleUserData" :key="item.user_key" :label="item.user_name" :value="item.user_key">
				</el-option>
			</el-select>
			<span slot="footer" class="dialog-footer">
			    <el-button @click="addCopyRole = false;">取 消</el-button>
			    <el-button type="primary" @click="addRoleUser">确 定</el-button>
			  </span>
		</el-dialog>
		
		<!-- 追加店铺权限 -->
		<el-dialog title="追加店铺权限" :visible.sync="addShopRoleVisible" width="30%" @close="handleClose">
			<el-select v-model="shopDictId" placeholder="请选择" @change="get_entity_right_val">
				<el-option v-for="item in shopDictArray" :key="item.dict_id" :label="item.detail_name" :value="item.dict_id" />
			</el-select>
			<el-select v-model="shopVal" placeholder="请选择">
				<el-option v-for="(item,index) in shopValArray" :key="item.index" :label="item.val" :value="item.val" />
			</el-select>
			<span slot="footer">
			    <el-button @click="resetShopData">取 消</el-button>
			    <el-button type="primary" @click="insert_entity_right">确 定</el-button>
			</span>					
		</el-dialog>
	</div>
</template>

<script>
	import { query, apiparas, execute } from '../../api/api';
	import { Cookie } from '../../js/common';
	import vTable from '../charts/table.vue';
	export default {
		components:{
            vTable
      	},
		data() {
			return {
				itemsDate:[
					{prop:'user_id',label:'用户ID'},
					{prop:'user_name',label:'用户姓名'},
					{prop:'sex',label:'性别'},
					{prop:'telphone',label:'联系电话'},
					{prop:'mobilephone',label:'手机'},
					{prop:'address',label:'联系地址'}
				],
				userDate: [],
				checkedRole: [],
				checkedRoleUser:[],
				p_user_name:'',
				text:'',
				editId:'',
				append:'',
				selectRow:{},
				multipleTable:[],
				noRoleUserData:[],
				RoleUserData:[],
				addFormVisible:false,
				addRoleVisible:false,
				addCopyRole:false,
				addForm:{
					user_id:'',
					user_name:'',
					sex:'男',
					telphone:'',
					mobilephone:'',
					address:''
					},
				isAddShow:false,
				isEditShow:false,
				editFormVisible:false,
				addFormRules: {
					user_id: [
				        { required: true, message: '请输入用户ID', trigger: 'blur' },
				        //{ validator: validaePass }
			        ],
			     	user_name: [
				        { required: true, message: '请输入用户姓名', trigger: 'blur' },
				        //{ validator: validaePass }
			        ],
			     	password: [
				        { required: true, message: '请输入初始密码', trigger: 'blur' },
				        //{ validator: validaePass }
			        ]
				},
				addShopRoleVisible:false,
				shopDictArray:[],
				shopDictId:'',
				shopValArray:[],
				shopVal:''
			}
		},
		mounted: function() {
			//生命周期
		},
		computed: {
			//计算属性
			company_key(){
				let company_key = Cookie.Get("company_key");
				return company_key;
			}
		},
		methods: { //函数
			handleSelectionChange(val){
				this.multipleTable = val;
			},
			handleClose() {
				this.checkedRole = [];
			},
		    reset:function(){//重置
				if (this.isEditShow) {
		            this.addForm.user_id = this.selectRow.user_id;
					this.addForm.user_name = this.selectRow.user_name;
					this.addForm.sex = this.selectRow.sex;
					this.addForm.telphone = this.selectRow.telphone;
					this.addForm.mobilephone = this.selectRow.mobilephone;
					this.addForm.address = this.selectRow.address;
				}else{
					this.addForm = {
						user_id:'',
						user_name:'',
						sex:'男',
						telphone:'',
						mobilephone:'',
						address:''
					}
				}
			},
			resetForm:function(formName){//重置
				this.$refs[formName].resetFields();
			},
			showdata: function() { //查询数据
				//显示数据
				let jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'user_name', this.p_user_name);
				//查询汇总
				let _paras = apiparas.getParas('default','basic|get_test_user', jsonparas);
				query(_paras).then(response => {
					let json_data = response.result;
					this.userDate = json_data;
					this.$notify({title: '成功信息',message: '数据加载完毕！',type: 'success'});
				});
			},
			//新增
			showAdd: function() {  //显示新增对话框
				this.addFormVisible = true;
				this.text = '新增';
				this.isEditShow = false;
				this.addForm = {
					user_id:'',
					user_name:'',
					sex:'男',
					telphone:'',
					mobilephone:'',
					address:''
				}
			},
			//编辑
			showEdit:function(index,row){
				this.addFormVisible = true;
				this.text = '编辑';	
				this.selectRow = row;
				this.addForm.user_id = row.user_id;
				this.addForm.user_name = row.user_name;
				this.addForm.sex = row.sex;
				this.addForm.telphone = row.telphone;
				this.addForm.mobilephone = row.mobilephone;
				this.addForm.address = row.address;
				this.editId = row.user_key;
				this.isEditShow = true;
			},

			addSubmit:function(){//提交
				if (this.isEditShow) {
					//增加查询条件
					let jsonparas = [
						{'name': 'user','value': this.editId},
						{'name': 'user_id','value':  this.addForm.user_id},
						{'name': 'user_name','value':this.addForm.user_name},
						{'name': 'sex','value': this.addForm.sex},
						{'name': 'telphone','value': this.addForm.telphone},
						{'name': 'mobilephone','value': this.addForm.mobilephone},
						{'name': 'address','value': this.addForm.address}
					]
					//查询汇总
					let _paras = apiparas.getParas('default','basic|update_user', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0){
							this.addFormVisible = false;
							this.$notify({title:'成功信息',message:'修改完成',type:'success'});
							this.showdata();
						}
						else
						{
							this.$notify.error({title: '错误',message:response.errmsg ,type:'error'});
						}
					});	
				}else{
					//处理添加
					//增加查询条件
					let jsonparas = [
						{'name': 'user_id','value':  this.addForm.user_id},
						{'name': 'user_name','value':this.addForm.user_name},
						{'name': 'sex','value': this.addForm.sex},
						{'name': 'telphone','value': this.addForm.telphone},
						{'name': 'mobilephone','value': this.addForm.mobilephone},
						{'name': 'address','value': this.addForm.address}
					];
					this.$notify({title: '信息提示',message: '正在加载数据，请稍后！',type: 'info'});
					//查询汇总
					let _paras = apiparas.getParas('default','basic|insert_user', jsonparas);
					execute(_paras).then(response => {
						if(response.errid == 0){
							this.addFormVisible = false;
							this.$notify({title:'成功信息',message:'添加完成',type:'success'});
							this.showdata();
						}
						else
						{
							this.$notify.error({title: '错误',message:response.errmsg ,type:'error'});
						}
					});					
				}
			},
			
			//删除
			showDel:function(){
				console.log(this.multipleTable);
				var keys = '';
				for(var i = 0; i < this.multipleTable.length; i++) {
					keys += this.multipleTable[i]['user_key'] + ",";
				}
				if (keys =='')
				{
					this.$notify({title: '信息提示',message: '请选择要删除的明细！',type: 'info'});
					return;
				}
				keys = keys.substring(0,keys.length-1);
				this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					var jsonparas=[];
					apiparas.pushPara(jsonparas,'keys',keys);
					let _paras = apiparas.getParas('default','basic|del_user',jsonparas);
					execute(_paras).then(response=>{
						var json_data = response.result;
						if(response.errid == 0){
							this.$notify({title:'删除',message:'成功删除用户',type:'success'});
							this.showdata();
						}
						else
						{
							this.$notify.error({title: '错误',message: response.errmsg});
						}
						
					});	
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
				
				
			},
			showExport:function() //导出
			{
				this.downloadLoading = true
				require.ensure([], () => {

					const {
						export_json_to_excel
					} = require('@../../vendor/Export2Excel')
					const tHeader = ['用户ID','用户姓名','性别','联系电话','手机','联系地址','创建时间','修改时间'];
					const filterVal = ['user_id','user_name','sex','telphone','mobilephone','address','create_time','update_time'];
					const list = this.userDate;
					const _data = this.formatJson(filterVal, list);
					export_json_to_excel(tHeader, _data, '用户管理','用户管理');
				})
			},
			showDistribution:function()
			{
				this.multipleTable = this.multipleTable;
				this.addRoleVisible = true;
				this.getNoRoleUserData();
			},
			showCopybution:function(type){
				this.multipleTable = this.multipleTable;
				this.addCopyRole = true;
				this.getRoleUserData();
				if(type == 0){
					this.append =0;
				}else{
					this.append =1;
				}
			},
			getNoRoleUserData: function() {
				var jsonparas = [];
				//增加查询条件
				apiparas.pushPara(jsonparas, 'role_name', '');
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_role', jsonparas);
				query(_paras).then(response => {
					this.noRoleUserData = response.result;
				});
			},
			getRoleUserData: function() {
				var jsonparas = [];
				//增加查询条件
				//查询汇总
				let _paras = apiparas.getParas('default', 'basic|get_user_copy', jsonparas);
				query(_paras).then(response => {
					this.RoleUserData = response.result;
				});
			},
			addRole() {
				var keys = '';
				for(var i = 0; i < this.multipleTable.length; i++) {
					keys += this.multipleTable[i]['user_key'] + ",";
				}
				keys = keys.substring(0, keys.length - 1);
				if(keys == '') {
					this.$notify({
						title: '信息提示',
						message: '请选择要把哪个用户添加到角色！',
						type: 'info'
					});
					return;
				}

				let str = '';
				for(let i = 0; i < this.checkedRole.length; i++) {
					str += this.checkedRole[i] + ','
				}
				str = str.substring(0, str.length - 1);
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'user_keys', keys);
				apiparas.pushPara(jsonparas, 'role_keys', str);
				let _paras = apiparas.getParas('default', 'basic|insert_role_user', jsonparas);
				console.log(_paras,'role_paras');
				execute(_paras).then(response => {
					this.addRoleVisible = false;
					this.showdata();
					this.checkedRole = [];
					if(response.errid == 0) {
						this.$message({
							showClose: true,
							message: '成功添加',
							type: 'success'
						});
					} else {

						this.$message({
							showClose: true,
							message: '添加失败',
							type: response.errmsg
						});
					}
				});
			},
			addRoleUser(){
				var keys = '';
				for(var i = 0; i < this.multipleTable.length; i++) {
					keys += this.multipleTable[i]['user_key'] + ",";
				}
				keys = keys.substring(0, keys.length - 1);
				if(keys == '') {
					this.$notify({
						title: '信息提示',
						message: '请选择要把哪个用户覆盖！',
						type: 'info'
					});
					return;
				}

				let str = '';
				for(let i = 0; i < this.checkedRoleUser.length; i++) {
					str += this.checkedRoleUser[i] + ','
				}
				str = str.substring(0, str.length - 1);
				var jsonparas = [];
				apiparas.pushPara(jsonparas, 'uers', str);
				apiparas.pushPara(jsonparas, 'userkey', keys);
				apiparas.pushPara(jsonparas, 'append', this.append);
				let _paras = apiparas.getParas('default', 'basic|copy_role_user', jsonparas);
				console.log(_paras,'_paras');
				execute(_paras).then(response => {
					console.log(response,'response');
					this.addRoleVisible = false;
					this.showdata();
					this.checkedRoleUser = [];
					if(response.errid == 0) {
						this.$message({
							showClose: true,
							message: '成功添加',
							type: 'success'
						});
					} else {

						this.$message({
							showClose: true,
							message: '添加失败',
							type: response.errmsg
						});
					}
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			tableRowClassName(row, rowIndex) {
				return '';
			},
			//店铺权限相关方法start
			showShopDialog(){
				if(this.multipleTable==null || this.multipleTable.length===0){
					this.$notify.error({title: '错误',message: "请选择用户"});
					return;
				}
				this.addShopRoleVisible = true;
				this.get_dict();
			},
			get_dict(){
				let jsonparas=[{"name": "dict_key","value": "108"}];
				let _paras = apiparas.getParas('default','sys|get_dict',jsonparas);
				execute(_paras).then(response=>{
					if(response.errid === 0){
						this.shopDictArray = response.result;
					}else{
						this.$notify.error({title: '错误',message: response.errmsg});
					}
				});					
			},
			get_entity_right_val(dict_id){
				this.shopVal = '';
				let jsonparas=[{"name": "dict_id","value": dict_id}];
				let _paras = apiparas.getParas('default','sys|get_entity_right_val',jsonparas);
				execute(_paras).then(response=>{
					if(response.errid === 0){
						this.shopValArray = response.result;
					}else{
						this.$notify.error({title: '错误',message: response.errmsg});
					}
				});		
			},
			insert_entity_right(){
				if(this.shopDictId===null || this.shopDictId==='' || this.shopVal===null || this.shopVal===''){
					this.$notify.error({title: '错误',message: '请选择'});
					return;
				}
				let userKey = [];
				for(let user of this.multipleTable){
					userKey.push(user.user_key);
				}
				let jsonparas=[
					{"name": "users","value": userKey.join(",")},
					{"name": "dict_id","value": this.shopDictId},
					{"name": "val","value": this.shopVal}
				];
				let _paras = apiparas.getParas('default','sys|insert_entity_right',jsonparas);
				execute(_paras).then(response=>{
					if(response.errid === 0){
						this.resetShopData();
						this.$message({ showClose: true, message: '成功', type: 'success'});
					}else{
						this.$notify.error({title: '错误',message: response.errmsg});
					}
				});		
			},
			resetShopData(){
				this.shopDictId = '';
				this.shopDictArray = [];
				this.shopVal = '';
				this.shopValArray = [];
				this.addShopRoleVisible = false;
			}
			//店铺权限相关方法end
		},
		created: function() {
			this.showdata();
		}
	}
</script>

<style>

</style>